package com.mall.common.ipseek;

import net.sf.json.JSONObject;
import org.springframework.stereotype.Service;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.ProtocolException;
import java.net.URL;
import java.util.HashMap;
import java.util.Map;

@Service
public class IPSeekerImpl implements IPSeeker {
	// 用来做为cache，查询一个ip时首先查看cache，以减少不必要的重复查找
	private Map<String, IPLocation> ipCache = new HashMap<String, IPLocation>();

	public IPLocation getIPLocation(String ip) {
		// 先检查cache中是否已经包含有这个ip的结果，没有再搜索文件
		if (ipCache.containsKey(ip)) {
			IPLocation ipLoc = ipCache.get(ip);
			return ipLoc;
		} else {
			IPLocation ipLoc = new IPLocation();
			try {
				URL url = new URL("http://ip.taobao.com/service/getIpInfo.php?ip=" + ip);
				HttpURLConnection htpcon = (HttpURLConnection) url.openConnection();
				htpcon.setRequestMethod("GET");
				htpcon.setDoOutput(true);
				htpcon.setDoInput(true);
				htpcon.setUseCaches(false);

				InputStream in = htpcon.getInputStream();
				BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(in));
				StringBuffer temp = new StringBuffer();
				String line = bufferedReader.readLine();
				while (line != null) {
					temp.append(line).append("\r\n");
					line = bufferedReader.readLine();
				}
				bufferedReader.close();
				JSONObject obj = JSONObject.fromObject(temp.toString());
				if (obj.getInt("code") == 0) {
					JSONObject data = obj.getJSONObject("data");
					ipLoc.setCountry(data.getString("country"));
					ipLoc.setArea(data.getString("region"));
					ipLoc.setCity(data.getString("city"));
					ipLoc.setIsp(data.getString("isp"));
				} else {
					
				}
			} catch (MalformedURLException e) {
				e.printStackTrace();
			} catch (ProtocolException e) {
				e.printStackTrace();
			} catch (IOException e) {
				e.printStackTrace();
			}
			ipCache.put(ip, ipLoc.getCopy());
			return ipLoc;
		}
	}

}
